<template>
  <!--商品详情页底部商品导航-->
  <div>
    <van-goods-action>
      <van-goods-action-icon :icon="isCollect?'star':'star-o'" :color="isCollect?'red':'#666'"
        :text="isCollect?'已收藏':'未收藏'" @click="collectGoods(!isCollect)" />
      <van-goods-action-icon :badge="$store.state.cartListLength" icon="shopping-cart-o" text="购物车" @click="goCart" />
      <van-goods-action-button type="warning" text="加入购物车" @click="addToCart" />
      <van-goods-action-button type="danger" text="立即购买" @click="onBuyClicked" />
    </van-goods-action>
  </div>
</template>

<script>
import { cancelCollect, collect } from '@/request/api.js'
import { mapGetters } from 'vuex'
export default {
  name: "MyGoodsActions",
  props: ["badge", "goodsId"],
  data() {
    return {
      //控制收藏显示
      isCollect: false,
      userId: 0,
    }
  },
  computed: {
    ...mapGetters(['collectGoodsIdList'])
  },
  mounted() {
    let userInfo = JSON.parse(localStorage.getItem('userInfo'))
    if (userInfo) this.userId = userInfo.id
    // this.goodsId = JSON.parse(this.$route.query.productDetail).id

    this.collectGoodsIdList.forEach(item => {
      if (item == this.goodsId) this.isCollect = true
    })
  },
  methods: {
    //去购物车页面
    goCart() {
      this.$router.push('/cart')
    },
    addToCart() {
      this.$emit('addToCart')
    },
    //初始化购物车数量
    initData() {

    },
    //收藏
    collectGoods(isCollect) {
      //发送到后台请求,收藏成功之后再更新状态
      if (localStorage.getItem('token')) {
        if (isCollect) {
          collect({ userId: this.userId, goodsId: this.goodsId }).then(res => {
            this.$toast.success(res.message)
          })
        } else {
          cancelCollect({ userId: this.userId, goodsId: this.goodsId }).then(res => {
            this.$toast.success(res.message)
          })
        }
        setTimeout(() => {
          this.isCollect = isCollect
        }, 0)
      } else {
        this.$toast.fail('请先登录!')
      }
    },
    onBuyClicked() {
      this.$parent.show = true
    },
  }
}
</script>

